<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>客户管理</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
  <div class="d-flex">
    <nav class="flex-column bg-dark text-white p-3" style="width: 220px; height: 100vh;">
      <h4>后台管理</h4>
      <ul class="nav flex-column">
        <li class="nav-item"><a href="/admin/customers" class="nav-link text-white active">客户管理</a></li>
        <li class="nav-item"><a href="/admin/cards" class="nav-link text-white">银行卡管理</a></li>
        <li class="nav-item"><a href="/admin/deposits" class="nav-link text-white">存款业务管理</a></li>
        <li class="nav-item"><a href="/admin/transactions" class="nav-link text-white">交易管理</a></li>
      </ul>
    </nav>
    <main class="flex-fill p-4">
      <h3>客户管理</h3>
      <button class="btn btn-success mb-2">新增客户</button>
      <button class="btn btn-info mb-2">导出CSV</button>
      <button class="btn btn-info mb-2" data-bs-toggle="modal" data-bs-target="#searchModal">查询</button>
      <table class="table table-bordered">
        <thead>
          <tr>
            <th>客户编号</th>
            <th>姓名</th>
            <th>身份证号</th>
            <th>联系电话</th>
            <th>联系地址</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody id="customers-tbody">
          <!-- JS渲染客户数据 -->
        </tbody>
      </table>
    </main>
  </div>
  <!-- 通用编辑/删除 Modal -->
  <div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <form id="editForm">
          <div class="modal-header">
            <h5 class="modal-title" id="modalTitle">编辑</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body" id="modalBody"></div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="submit" class="btn btn-primary" id="modalSaveBtn">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>
  <!-- 查询Modal -->
  <div class="modal fade" id="searchModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <form id="searchForm">
          <div class="modal-header">
            <h5 class="modal-title">查询条件</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <input type="text" class="form-control mb-2" id="searchCustomerID" placeholder="客户编号">
            <input type="text" class="form-control mb-2" id="searchCustomerName" placeholder="姓名">
            <input type="text" class="form-control mb-2" id="searchPID" placeholder="身份证号">
            <input type="text" class="form-control mb-2" id="searchTelephone" placeholder="电话">
            <input type="text" class="form-control mb-2" id="searchAddress" placeholder="地址">
            <input type="number" class="form-control mb-2" id="searchStartID" placeholder="起始编号">
            <input type="number" class="form-control mb-2" id="searchEndID" placeholder="结束编号">
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="submit" class="btn btn-primary">确定</button>
          </div>
        </form>
      </div>
    </div>
  </div>
  <script src="/static/js/main.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
  async function loadCustomers() {
    const res = await fetch('/api/admin/customers');
    const data = await res.json();
    const tbody = document.getElementById('customers-tbody');
    tbody.innerHTML = '';
    data.forEach(c => {
      tbody.innerHTML += `<tr>
        <td>${c.customerID}</td>
        <td>${c.customerName}</td>
        <td>${c.PID}</td>
        <td>${c.telephone}</td>
        <td>${c.address}</td>
        <td>
          <button class='btn btn-sm btn-primary' onclick='openEditModal(${JSON.stringify(c)})'>编辑</button>
          <button class='btn btn-sm btn-danger' onclick='openDeleteModal("${c.customerID}")'>删除</button>
        </td>
      </tr>`;
    });
  }
  document.addEventListener('DOMContentLoaded', loadCustomers);

  // 新增客户
  if(document.querySelector('.btn-success')){
    document.querySelector('.btn-success').onclick = function() {
      document.getElementById('modalTitle').innerText = '新增客户';
      document.getElementById('modalBody').innerHTML = `
        <div class="mb-3">
          <label class="form-label">姓名</label>
          <input type="text" class="form-control" id="editCustomerName">
        </div>
        <div class="mb-3">
          <label class="form-label">身份证号</label>
          <input type="text" class="form-control" id="editPID">
        </div>
        <div class="mb-3">
          <label class="form-label">联系电话</label>
          <input type="text" class="form-control" id="editTelephone">
        </div>
        <div class="mb-3">
          <label class="form-label">联系地址</label>
          <input type="text" class="form-control" id="editAddress">
        </div>
      `;
      document.getElementById('modalSaveBtn').onclick = saveNewCustomer;
      new bootstrap.Modal(document.getElementById('editModal')).show();
    };
  }
  async function saveNewCustomer(e) {
    e.preventDefault();
    const customerName = document.getElementById('editCustomerName').value;
    const PID = document.getElementById('editPID').value;
    const telephone = document.getElementById('editTelephone').value;
    const address = document.getElementById('editAddress').value;
    const res = await fetch('/api/admin/customers', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ customerName, PID, telephone, address })
    });
    if ((await res.json()).msg === '客户添加成功') {
      alert('新增成功');
      location.reload();
    } else {
      alert('新增失败');
    }
  }
  // 编辑客户
  function openEditModal(c) {
    document.getElementById('modalTitle').innerText = '编辑客户';
    document.getElementById('modalBody').innerHTML = `
      <input type="hidden" id="editCustomerID" value="${c.customerID}">
      <div class="mb-3">
        <label class="form-label">姓名</label>
        <input type="text" class="form-control" id="editCustomerName" value="${c.customerName}">
      </div>
      <div class="mb-3">
        <label class="form-label">身份证号</label>
        <input type="text" class="form-control" id="editPID" value="${c.PID}">
      </div>
      <div class="mb-3">
        <label class="form-label">联系电话</label>
        <input type="text" class="form-control" id="editTelephone" value="${c.telephone}">
      </div>
      <div class="mb-3">
        <label class="form-label">联系地址</label>
        <input type="text" class="form-control" id="editAddress" value="${c.address}">
      </div>
    `;
    document.getElementById('modalSaveBtn').onclick = saveEditCustomer;
    new bootstrap.Modal(document.getElementById('editModal')).show();
  }
  async function saveEditCustomer(e) {
    e.preventDefault();
    const customerID = document.getElementById('editCustomerID').value;
    const customerName = document.getElementById('editCustomerName').value;
    const PID = document.getElementById('editPID').value;
    const telephone = document.getElementById('editTelephone').value;
    const address = document.getElementById('editAddress').value;
    const res = await fetch(`/api/admin/customers/${customerID}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ customerName, PID, telephone, address })
    });
    if ((await res.json()).msg === '客户信息已更新') {
      alert('保存成功');
      location.reload();
    } else {
      alert('保存失败');
    }
  }
  // 删除客户
  function openDeleteModal(customerID) {
    document.getElementById('modalTitle').innerText = '删除确认';
    document.getElementById('modalBody').innerHTML = `<p>确定要删除客户编号 ${customerID} 吗？</p>`;
    document.getElementById('modalSaveBtn').onclick = function(e) {
      e.preventDefault();
      deleteCustomer(customerID);
    };
    new bootstrap.Modal(document.getElementById('editModal')).show();
  }
  async function deleteCustomer(customerID) {
    const res = await fetch(`/api/admin/customers/${customerID}`, { method: 'DELETE' });
    if ((await res.json()).msg === '客户已删除') {
      alert('删除成功');
      location.reload();
    } else {
      alert('删除失败');
    }
  }
  document.getElementById('searchForm').onsubmit = async function(e) {
    e.preventDefault();
    const params = new URLSearchParams({
      customerID: document.getElementById('searchCustomerID').value,
      customerName: document.getElementById('searchCustomerName').value,
      PID: document.getElementById('searchPID').value,
      telephone: document.getElementById('searchTelephone').value,
      address: document.getElementById('searchAddress').value,
      start_id: document.getElementById('searchStartID').value,
      end_id: document.getElementById('searchEndID').value
    });
    const res = await fetch('/api/admin/customers/search?' + params.toString());
    const data = await res.json();
    const tbody = document.getElementById('customers-tbody');
    tbody.innerHTML = '';
    data.forEach(c => {
      tbody.innerHTML += `<tr>
        <td>${c.customerID}</td>
        <td>${c.customerName}</td>
        <td>${c.PID}</td>
        <td>${c.telephone}</td>
        <td>${c.address}</td>
        <td>
          <button class='btn btn-sm btn-primary' onclick='openEditModal(${JSON.stringify(c)})'>编辑</button>
          <button class='btn btn-sm btn-danger' onclick='openDeleteModal("${c.customerID}")'>删除</button>
        </td>
      </tr>`;
    });
    bootstrap.Modal.getInstance(document.getElementById('searchModal')).hide();
  };
  </script>
</body>
</html>